//存储 用户token、tentId、主界面模块、模块菜单信息
import type { UserInfoResult, StateType } from '@/types/piniatypes';
import { defineStore } from 'pinia';

//用户数据存储
export const authStore = defineStore('authStore', {
  state: () : StateType =>({
      token : '',
      tenantId : '',
      auth_moduleInfos : [], //有权限的模块信息
      auth_serverMenuInfos: new Map(), //有权限的系统菜单  // k,模块名称   v模块菜单信息
      userInfo : {
        id: '',
        userName: '',
        nickName: '',
        userType: '',
        sex: '',
        email: '',
        deptId: '',
        tenantId: '',
        phoneNumber: '',
        avatar: '',
        roles: [],
        rolesName: []
      }
  }),
  persist:[
    {
      storage:localStorage,
      paths:['token'],
      key:'BOOT_INDUSTRY_TOKEN'
    },
    {
      storage:localStorage,
      paths:['userInfo'],
      key:'user_info'
    },
    {
      storage:localStorage,
      paths:['tentId'],
      key:'tentId'
    }
  ],
  getters:{
    getToken(): string {
      return this.token ;
    },
    getTentId(): string {
      return this.tenantId;
    },
    getUserInfo() : UserInfoResult {
      return this.userInfo;
    },
    getAuthModuleInfos() : object[] {
      return this.auth_moduleInfos;
    },
    getAuthServerMenuInfos() : Map<string,[]> {
      return this.auth_serverMenuInfos;
    },
  },
  actions: {
    SET_TOKEN(tokenn : string) {
        if(tokenn){
            this.token = tokenn;
        }
    },
    SET_TENTID(tentId : string) {
        if(tentId){
            this.tenantId = tentId;
        }
    },
    async SET_USERINFO(userInfo : UserInfoResult){
      console.log(userInfo)
      const validateInfos = userInfo && userInfo.id && userInfo.tenantId;
      if(validateInfos){
        this.userInfo = userInfo;
        return Promise.resolve();
      }else{
        console.error("userinfo has null property value !")
        Promise.reject("UserInfo Values has null")
      }
    },
    //设置主模块数据
    SET_MODULEINFOS(modules: []){
        this.auth_moduleInfos = modules;
    },
    //设置业务服务菜单数据
    SET_SERVER_MENUINFOS(typs:string, val: []){
        if(typs){
            if(!val){
                this.auth_serverMenuInfos.delete(typs);
            }else{
                this.auth_serverMenuInfos.set(typs,val);
            }
        }
    },
    CLEAR_USERINFO(){
      this.tenantId = '';
      this.auth_moduleInfos = [];
      this.auth_serverMenuInfos.clear();
      this.userInfo = {
        id: '',
        userName: '',
        nickName: '',
        userType: '',
        sex: '',
        email: '',
        deptId: '',
        tenantId: '',
        phoneNumber: '',
        avatar: '',
        roles: [],
        rolesName: []
      }
    },
    REMOVE_TOKEN(){
      this.token = '';
    }
  }
})
